
package de.godlike.autobackup;

import org.apache.log4j.Logger;

import java.io.File;
import java.util.ArrayList;

public class JAutoBackup {

    private File folderToCheck;

    private static final String PROP_BACKUP_FOLDER_KEY = "JAutoBackup.backupFolder";

    private static final String PROP_WATCH_FOLDER_KEY = "JAutoBackup.folderToWatch";

    static Logger logger;

    public void watch() {
        logger.info("Start watching folder " + Messages.getString(PROP_WATCH_FOLDER_KEY));
        logger.info("All files will be copied to folder "
                + Messages.getString(PROP_BACKUP_FOLDER_KEY));

        ArrayList<File> watchedFiles = new ArrayList<File>();

        // Start daemon here
        while (true) {
            File filesToWatch[] = folderToCheck.listFiles();

            for (File file : filesToWatch) {
                logger.debug("Checking if file should be watched: " + file.getAbsolutePath());
                if (file.isDirectory()) {
                    continue;
                }
                boolean isWatched = false;
                for (File fileToCheck : watchedFiles) {
                    if (fileToCheck.getAbsolutePath().equalsIgnoreCase(file.getAbsolutePath())) {
                        isWatched = true;
                        break;
                    }
                }

                if (isWatched) {
                    logger.debug("File " + file.getAbsolutePath()
                            + " allready exists in list -> skipping");
                    continue;
                }

                watchedFiles.add(file);
                logger.debug("Adding file to watchlist: " + file.getAbsolutePath());
                new Watchdog(file);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                logger.warn("Could not sleep", e);
            }
        }
    }

    public JAutoBackup(String folderToWatch, String backupFolder) {
        logger = Logger.getLogger(this.getClass());
        folderToCheck = new File(folderToWatch);
    }

    public static void main(String[] args) {

        JAutoBackup bUp = new JAutoBackup(Messages.getString(PROP_WATCH_FOLDER_KEY),
                Messages.getString(PROP_BACKUP_FOLDER_KEY));
        bUp.watch();
        logger.info("Beende JAutoBackup - Diese Stelle sollte nicht erreicht werden");
    }

}
